using System;
using FluentNHibernate;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace HashFoo.Nhib
{
    /// <summary>
    /// Creates human readable names for foriegn key relationships.
    /// </summary>
    public class CustomFkNameConvention :
        IReferenceConvention,
        IKeyManyToOneConvention,
        IHasManyToManyConvention,
        IHasManyConvention
    {
        /// <summary>
        /// Apply changes to the target
        /// </summary>
        public void Apply(IManyToOneInstance instance)
        {
            instance.ForeignKey("FK_" + instance.Name + "_" + (instance.EntityType ?? instance.Property.DeclaringType).Name);
        }

        /// <summary>
        /// Apply changes to the target
        /// </summary>
        public void Apply(IKeyManyToOneInstance instance)
        {
            instance.ForeignKey("FK_" + instance.Name + "_" + (instance.EntityType ?? instance.Class.GetUnderlyingSystemType()).Name);
        }

        /// <summary>
        /// Apply changes to the target
        /// </summary>
        public void Apply(IManyToManyCollectionInstance instance)
        {
            instance.Relationship.ForeignKey("FK_" + instance.Relationship.Class.Name + "_" + instance.TableName);
        }

        /// <summary>
        /// Apply changes to the target
        /// </summary>
        public void Apply(IOneToManyCollectionInstance instance)
        {
        }
    }
}